<template>
	<view>
		
		<view class="upload-wrap">
			<view class="upload-btn" @click="handleUploadClick">
<!-- 				<uni-row>
					<uni-col :span="24"> -->
						<button :plain="true" size="mini" class="btn-cls">
							<text class="btn-text-request-cls" v-if="isRequir">*</text>
							{{btnName}}
						</button>
<!-- 					</uni-col>
				</uni-row> -->
			</view>
			<!-- <view class="mgb-16 file-wrap">
				<view class="btn-click file-line">
					<uni-row style="width: 100%;">
						<uni-col :span="8">
							<view class="file-info">
								文件名
							</view>
						</uni-col>
						<uni-col :span="4">
							大小
						</uni-col>
						<uni-col :span="4">
							状态
						</uni-col>
						<uni-col :span="8">
							<view style="text-align: center;">
								操作
							</view>
						</uni-col>
					</uni-row>
				</view>
			</view> -->

			<!-- <view class="mgb-16 file-wrap" v-for="(item, index) in fileList" :key="curTime">
				<view class="btn-click file-line" @click="handlePreview(item)">
					<uni-row style="width: 100%;">
						<uni-col :span="8">
							<view class="file-info">
								<image :src="icons[item.fileType || 'file']" mode="aspectFill" class="file-icon" />
								<text class="file-name">{{ item.name || title[type] }}</text>
							</view>
						</uni-col>
						<uni-col :span="4">
							{{(item.size/1000).toFixed(1)}}k
						</uni-col>
						<uni-col :span="4">
							<view v-if="item.status==0">
								待上传
							</view>
							<view v-else-if="item.status==1">
								{{item.progress}}%
							</view>
							<view v-else>
								上传成功
							</view>
						</uni-col>
						<uni-col :span="8">
							<view style="text-align: center;">

								<text style="padding: 5rpx 10rpx;border: 1rpx solid blue;color: blue;"
									@click.stop="handleDeleteFile(index)">删除</text>
								<text
									style="padding: 5rpx 10rpx;border: 1rpx solid blue;color: blue;margin-left: 10rpx;"
									@click.stop="upload(item)">上传</text>
							</view>
						</uni-col>
					</uni-row>


				</view>
			</view> -->
			<!-- <view class="mgb-16 file-wrap" v-if="fileList.length === 0 && disabled">
				<view class="file-line">
					<text class="file-empty">暂无数据</text>
				</view>
			</view> -->
		</view>
		<XeUpload ref="XeUpload"  @callback="handleUploadCallback"></XeUpload>
	</view>
</template>

<script>
	import XeUpload from '../xe-upload/xe-upload.vue'
	export default {
		name: 'chuizi-upload-file',
		components: {
			XeUpload
		},
		props: {
			type: {
				default: 'image', // image, video, file
				type: String,
			},
			list: {
				default: () => ([]),
				type: Array,
			},
			disabled: {
				default: false,
				type: Boolean,
			},
			btnName: {
				type: String,
				default: '上传文件'

			},
			isRequir: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				
				fileList: [],
				title: {
					image: '图片',
					video: '视频',
					file: '文件',
				},
				icons: {
					upload: '/static/uploadFile/icon_upload.png',
					close: '/static/uploadFile/icon_close.png',
					image: '/static/uploadFile/icon_image.png',
					video: '/static/uploadFile/icon_video.png',
					file: '/static/uploadFile/icon_file.png',
				},
				progress: '待上传',
				curTime: new Date().getTime(),
				
			};
		},
		watch: {
			list: {
				handler(val) {
					this.fileList = val || [];
				},
				immediate: true,
				deep: true,
			},
		},
		computed:{
			
		},
		mounted() {
			
		
			
		},
		methods: {
			handleUploadClick() {
				// 使用默认配置则不需要传入第二个参数
				// App、H5 文件拓展名过滤 { extension: ['.doc', '.docx'] } 或者 { extension: '.doc, .docx' }
				// this.$refs.XeUpload.upload(this.type);
				this.$refs.XeUpload.upload(this.type, {
					extension: ['application/pdf', 'application/msword',
						'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
					]
				});
				// 可以根据当前的平台，传入选择文件的参数，例如
				// 注意 当chooseMedia可用时，会优先使用chooseMedia
				// // uni.chooseImage
				// this.$refs.XeUpload.upload(type, {
				// 	count: 6,
				// 	sizeType: ['original', 'compressed'],
				// 	sourceType: ['album'],
				// });
				// // uni.chooseVideo
				// this.$refs.XeUpload.upload(type, {
				// 	sourceType: ['camera', 'album'],
				// });
				// // uni.chooseMedia (微信小程序2.10.0+;抖音小程序、飞书小程序;京东小程序支持)
				// this.$refs.XeUpload.upload(type, {
				// 	count: 9,
				// 	sourceType: ['album', 'camera'],
				// });
			},
			handleUploadCallback(e) {
				console.log('UploadCallback', e);
				this.curTime = new Date().getTime()
				if (['choose', 'success'].includes(e.type)) {
					// 根据接口返回修改对应的response相关的逻辑
					const tmpFiles = (e.data || []).map(({
						response,
						tempFilePath,
						name,
						fileType,
						size,
						status,
						progress
					}) => {
						// 当前测试服务返回的数据结构如下
						// {
						//   "result": {
						//       "fileName": "fileName",
						//       "filePath": `http://192.168.1.121:3000/static/xxxxx.png`,
						//   },
						//   "success": true,
						// }
						const res = response?.result || {};
						const tmpUrl = res.filePath ?? tempFilePath;
						const tmpName = res.fileName ?? name;
						const statusInit = 0
						const progressInit = 0
						return {
							...res,
							url: tmpUrl,
							name: tmpName,
							fileType,
							size,
							status: statusInit,
							progress: progressInit
						};
					});
					this.fileList.push(...tmpFiles);
					this.$emit("doneUpload", this.fileList);
				}
			},

			// 预览
			handlePreview({
				url
			}) {
				console.log('PreviewFile', url);
				const fileType = this.getFileType(url);
				if (fileType === 'image') {
					return uni.previewImage({
						current: url,
						urls: [url],
					});
				}
				// #ifndef H5
				if (fileType === 'office') {
					return uni.openDocument({
						filePath: url,
						fail: (err) => {
							console.log(err);
							uni.showToast({
								icon: 'none',
								title: '文件预览失败'
							});
						},
					});
				}
				// #endif
				uni.showModal({
					title: '提示',
					content: url,
					showCancel: false,
				});
			},
			handleDeleteFile(index) {
				let that = this
				uni.showModal({
					title: "提示",
					content: "是否要删除该文件?",
					success: function(res) {
						if (res.confirm) {

							that.fileList.splice(index, 1);
							that.$emit("doneUpload", that.fileList);
						} else if (res.cancel) {

						}
					}

				})

			},
			upload(item) {
				console.log('upload---------->', item);
				let that = this
				uni.showLoading({
					title: '上传中',
				})
				item.status = 1
				that.curTime = new Date().getTime()
				let header = {

				}
				// header["Content-Type"] = "application/form-data"
				// header["AuthorizationToken"] = uni.getStorageSync("token")

				const uploadTask = uni.uploadFile({
					url: "http://192.168.0.130:9022/downLoad/testup",
					filePath: item.url,
					name: 'file',
					method: 'POST',
					header: header,
					formData: {},
					success: ((res) => {
						console.log("上传文件", res)
						uni.hideLoading();
						let data = JSON.parse(res.data)
						let status = data.status;
						if (status !== 200) {
							return uni.showToast({
								title: '上传失败',
								icon: "error"
							})
						} else {
							item.status = 2
							that.curTime = new Date().getTime()
							item.successUrl = data.data
							that.$emit("doneUpload", that.fileList);
						}
						// JSON.parse(res.data)


					}),
					fail: (err) => {
						console.log(err)
						uni.hideLoading();
						uni.showToast({
							title: '上传失败',
							icon: "error"
						})

					}
				})
				uploadTask.onProgressUpdate((res) => {
					item.progress = res.progress
					that.curTime = new Date().getTime()
					console.log('上传进度' + that.progress);
					// console.log('已经上传的数据长度' + res.totalBytesSent);
					// console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);

					// 测试条件，取消上传任务。
					// if (res.progress > 50) {
					// 	uploadTask.abort();
					// }
				});
			},

			/**
			 * 获取文件类型
			 * @param {String} fileName 文件链接
			 * @returns {String} fileType => '', image, video, audio, office, unknown
			 */
			getFileType(fileName = '') {
				const flieArr = fileName.split('.');
				let suffix = flieArr[flieArr.length - 1];
				if (!suffix) return '';
				suffix = suffix.toLocaleLowerCase();
				const image = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp'];
				if (image.includes(suffix)) return 'image';
				const video = ['mp4', 'm4v'];
				if (video.includes(suffix)) return 'video';
				const audio = ['mp3', 'm4a', 'wav', 'aac'];
				if (audio.includes(suffix)) return 'audio';
				const office = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'plain'];
				if (office.includes(suffix)) return 'office';
				return 'unknown';
			},
		},
	};
</script>

<style lang="scss" scoped>
	view {
		box-sizing: border-box;
	}

	.btn-click {
		transition: all 0.3s;
		opacity: 1;
	}

	.btn-click:active {
		opacity: 0.5;
	}

	.mgb-16 {
		// margin-bottom: 16rpx;

		&:last-child {
			margin-bottom: 0;
		}
	}

	.upload-wrap {
		width: 100%;
		border-radius: 16rpx;
		background: white;
		margin: 20rpx;
		height: 100%;
		// padding: 32rpx;

		.upload-btn {
			text-align: left;
		height: 100%;
			margin-top: 20rpx;
			margin-bottom: -10rpx;
		}

		.file-wrap {
			margin-top: 20rpx;
			.file-line {
				width: 100%;
				background: #F5F5F5;
				border-radius: 8rpx;
				padding: 16rpx;
				font-size: 26rpx;
				color: #1A1A1A;
				line-height: 40rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.file-info {
					width: 90%;
					display: flex;
					align-items: center;
					text-align: left;

					.file-name {
						max-width: 80%;
						padding-left: 16rpx;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}
				}

				.file-icon {
					width: 40rpx;
					height: 40rpx;
					flex-shrink: 0;
				}

				.file-empty {
					color: #999999;
				}
			}
		}
	}

	.btn-cls {
		border-color: #c2c2c2;

		.btn-text-request-cls {
			color: red;
		}
	}
</style>